import Vue from 'vue'
import axios from 'axios'
import Moment from 'moment'
import { Message } from 'element-ui'
import { CONSTANT_OBJ } from '@/utils/constant'
// const { URL, ENV, PREFIX } = CONSTANT_OBJ
const { PREFIX } = CONSTANT_OBJ
// 存储cookies
export function setCookie (name, value) {
  const Days = 30
  const exp = new Date()
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
  document.cookie = name + '=' + escape(value) + ';path=/;'
}

// 读取cookies
export function getCookie (name) {
  const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')

  let arr
  return (arr = document.cookie.match(reg)) ? unescape(arr[2]) : null
}

// 删除cookies
export function delCookie (name) {
  setCookie(name, '')
}

// 对象深拷贝
export function deepCopy (src, dest) {
  dest = dest || {}

  for (let item in src) {
    if ((typeof src[item] === 'object') && src[item] !== null) {
      dest[item] = src[item].constructor === Array ? [] : {}
      deepCopy(src[item], dest[item])
    } else {
      dest[item] = src[item]
    }
  }

  return dest
}

/**
 * @param {String} text 需要复制的内容
 * @return {Boolean} 复制成功:true或者复制失败:false  执行完函数后，按ctrl + v试试
*/
export function copyText (text) {
  var textareaC = document.createElement('textarea')
  textareaC.setAttribute('readonly', 'readonly') // 设置只读属性防止手机上弹出软键盘
  textareaC.value = text
  document.body.appendChild(textareaC) // 将textarea添加为body子元素
  textareaC.select()
  var res = document.execCommand('copy')
  document.body.removeChild(textareaC) // 移除DOM元素
  Message({ message: '复制成功', type: 'success' })
  return res
}

// 获取url地址参数
export function getQueryParam (name) {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  let r = window.location.search.substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
}

export function checkPasswordStrength (rule, value, callback) {
  if (value === '') {
    callback(new Error('请输入新密码'))
    return
  }
  if (value.length > 16 || value.length < 8) {
    callback(new Error('密码长度必须为8~16位'))
    return
  }
  let strengthLen = 0
  if (value.length >= 8) {
    if (value.match(/\d+/)) {
      strengthLen++
    }
    if (value.match(/[a-z]+/)) {
      strengthLen++
    }
    if (value.match(/[A-Z]+/)) {
      strengthLen++
    }
    if (value.match(/[-`~!@#$%^&*()_+<>?:\\'{},=./;'[\]]/)) {
      strengthLen++
    }
  }
  console.log(strengthLen)
  if (strengthLen >= 3) {
    callback()
  } else {
    callback(new Error('至少包含数字、字母、大写字母、特殊符号中的3种'))
  }
}

// 导出excel
export function exportExcel (path, params, name = '') {
  let url
  let locationHref = `http://${window.location.hostname}` // 浏览器当前的url ip 不含端口
  url = locationHref 
  let finalPath = url + PREFIX + path
  const headers = {
    'Content-Type': 'application/json',
    'X-access-token': getCookie('usertoken'),
    'systemFlag': 4
  }

  axios({
    url: finalPath,
    method: 'post',
    withCredentials: true,
    responseType: 'blob',
    headers,
    data: params
  }).then(res => {
    var blob = new Blob([res.request.response], { type: 'text/xls' })
    var csvUrl = window.URL.createObjectURL(blob)
    var date = Moment().format('YY-MM-DD')
    var fileName = name + `(${date}).xls`
    var link = document.createElement('a')
    link.style.display = 'none'
    link.href = csvUrl
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    console.log(link.href)
    link = null
  }).catch(error => {
    console.log(error)
  })
}

// 下载合同
export function downloadWord (path, params, name = '') {
  let url
  let locationHref = `http://${window.location.hostname}` // 浏览器当前的url ip 不含端口
  url = locationHref 
  let finalPath = url + PREFIX + path
  const headers = {
    'Content-Type': 'application/json',
    'X-access-token': getCookie('usertoken'),
    'systemFlag': 4
  }

  axios({
    url: finalPath,
    method: 'post',
    withCredentials: true,
    responseType: 'blob',
    headers,
    data: params
  }).then(res => {
    var blob = new Blob([res.request.response], { type: 'application/msword' })
    var csvUrl = window.URL.createObjectURL(blob)
    var date = Moment().format('YY-MM-DD')
    var fileName = name + `(${date}).doc`
    var link = document.createElement('a')
    link.style.display = 'none'
    link.href = csvUrl
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    console.log(link.href)
    link = null
  }).catch(error => {
    console.log(error)
  })
}
// 下载pdf
export function downLoadContract (path, name = '') {
  let locationHref = `http://${window.location.host}`
  let finalPath = locationHref + path
  const headers = {
    'Content-Type': 'application/json',
    'X-access-token': getCookie('usertoken'),
    'systemFlag': 4,
  }

  axios({
    url: finalPath,
    method: 'post',
    withCredentials: true,
    responseType: 'blob',
    headers
  }).then(res => {
    var blob = new Blob([res.request.response], { type: 'application/pdf;chartset=UTF-8' })
    var csvUrl = window.URL.createObjectURL(blob)
    var date = Moment().format('YY-MM-DD')
    var fileName = name + `(${date}).pdf`
    var link = document.createElement('a')
    link.style.display = 'none'
    link.href = csvUrl
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    console.log(link.href)
    link = null
  }).catch(error => {
    console.log(error)
  })
}

export const disposePhone = (phone) => {
  if (phone.length === 11) {
    return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
  } else {
    return phone.replace(/.{4}$/, '*****')
  }
}
export const encryptIdNo = (card) => {
  if (!card) {
    return ''
  } else {
    return card.replace(/(\d{4})\d*(\d{4})/, '$1***********$2')
  }
}
export const encryptName = (name) => {
  if (!name) {
    return ''
  } else {
    if (name.length === 2) {
      return `${name.substring(0, 1)}*`
    } else if (name.length === 3) {
      return `${name.substring(0, 1)}*${name.substring(2, 3)}`
    } else if (name.length > 3) {
      return `${name.substring(0, 1)}*${name.substring(3, name.length)}`
    } else {
      return name
    }
  }
}
export const formatWithMod = (number) => {
  let n = number
  let r = ''
  let temp = ''
  let mod
  do {
    mod = n % 1000
    n = n / 1000
    temp = ~~mod
    r = (n >= 1 ? `${temp}`.padStart(3, '0') : temp) + (r ? ',' + r : '')
  } while (n >= 1)
  const strNumber = number + ''
  let index = strNumber.indexOf('.')
  if (index >= 0) {
    r += strNumber.substring(index)
  }
  return r
}
export const disposeAddress = (type, address) => {
  if (type === 'idcard') {
    return `${address.slice(0, 6)}****`
  } else {
    return `*******`
  }
}
export const disposeComName = (name) => {
  if (name.length > 5) {
    return `${name.slice(0, 2)}****${name.slice(-3)}`
  } else if (name.length <= 5) {
    return `${name.slice(0, 1)}****${name.slice(-2)}`
  }
}
export const filterPermissionTebs = (list) => {
  let res = []
  list.forEach(v => {
    if (Vue.prototype.$_permission(v.isPermission)) {
      res.push(v)
    }
  })
  return {
    activeName: res.length > 0 ? res[0].name : '',
    newTabs: [...res]
  }
}

// 加密除前4位以外的数据
export const encryptStr = (str) => {
  if (str.length > 5) {
    return `${str.slice(0, 4)}***`
  } else if (str.length <= 5) {
    return `${str.slice(0, 1)}***`
  }
}

/**
 * @description 获取在当前队列的停留时间
 * @param nowTime {string} 当前时间
 * @param apportionTime {string} 任务创建时间
 * @returns 队列停留时间（分钟）
 */
export const getResidenceTime = (apportionTime) => {
  let nowTime = new Date().getTime()
  let createTime = new Date(apportionTime).getTime()
  let result = parseInt(Math.abs(nowTime - createTime) / 1000 / 60)
  return result.toString()
}